package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.apache.catalina.startup.SetContextPropertiesRule;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private CacheClient cacheClient;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Blog getBlogById(Long id) {
        //获取blog信息
        Blog blog = this.getById(id);
        //组装用户信息
        User user = cacheClient.get(User.class, RedisConstants.CACHE_USER_KEY, blog.getUserId(), userService::getById, RedisConstants.CACHE_USER_TTL, TimeUnit.SECONDS);
        Boolean like = this.isLike(id);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        blog.setIsLike(like);
        return blog;
    }

    @Override
    public Result like(Long id) {
        //1.获取点赞列表
        Boolean islike = this.isLike(id);
        //2.未点赞则点赞存入数据库
        Long userId = UserHolder.getUser().getId();
        if (!islike) {
            //更新至缓存
            stringRedisTemplate.opsForZSet().add(RedisConstants.LIKE_BLOG_KEY + id, userId.toString(), System.currentTimeMillis());
            //更新至数据库
            this.update().setSql("liked = liked + 1").eq("id", id).update();
        } else {
            //3.已点赞取消点赞并存入数据库
            stringRedisTemplate.opsForZSet().remove(RedisConstants.LIKE_BLOG_KEY + id, userId.toString());
            this.update().setSql("liked = liked - 1").eq("id", id).update();
        }
        return Result.ok();
    }

    @Override
    public Result hot(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Boolean like = this.isLike(blog.getId());
            blog.setIsLike(like);
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        return Result.ok(records);
    }

    @Override
    public Result getLikes(Long id) {
        //查询点赞时间的top5
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(RedisConstants.LIKE_BLOG_KEY + id, 0, 5);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.EMPTY_LIST);
        }
        //解析中其中的用户id
        List<Long> list = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", list);
        //根据用户id查询出用户
        List<User> users = userService.query().in("id", list).last("ORDER BY FIELD(id," + idStr + ")").list();
        //处理用户规范
        List<UserDTO> userList = users.stream().map(user ->
                BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean save = this.save(blog);
        //推送至粉丝消息缓存
        if (save) {
            List<Follow> list = followService.lambdaQuery().eq(Follow::getFollowUserId, user.getId()).list();
            if (list != null || !list.isEmpty()) {
                list.forEach(follow -> stringRedisTemplate.opsForZSet().add(RedisConstants.FOLLOW_BLOG + follow.getUserId(), blog.getId().toString(),System.currentTimeMillis()));
            }
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result scrollRefresh(String lastId, Long offset) {
        Long userid = UserHolder.getUser().getId();
        //获取缓存中的消息id
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(RedisConstants.FOLLOW_BLOG+userid, 0, Double.valueOf(lastId), offset, 5);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok(Collections.EMPTY_LIST);
        }
        List ids = new ArrayList<>(typedTuples.size());
        long lastTime = 0;
        int so = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String value = typedTuple.getValue();
            ids.add(value);
            //如果最后的score相同或则需偏移量加一
            long time = typedTuple.getScore().longValue();
            if (time == lastTime) {
                so++;
            } else {
                so = 1;
                lastTime = time;
            }
        }
        String idStr = StrUtil.join(",", ids);
        //获取到id去查询Blog
        List<Blog> list = this.lambdaQuery().in(Blog::getId, ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        //查看是否点过赞
        list.forEach(blog->{
            blog.setIsLike(this.isLike(blog.getId()));
            User user = userService.getById(blog.getUserId());
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(list);
        scrollResult.setOffset(so);
        scrollResult.setMinTime(lastTime);
        return Result.ok(scrollResult);
    }


    public Boolean isLike(Long id) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return false;
        }
        Long userId = user.getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.LIKE_BLOG_KEY + id, userId.toString());
        return score != null ? true : false;
    }
}
